import { defineStore, storeToRefs } from 'pinia'
import { ElMessage } from 'element-plus'
import { getLocalStore, setLocalStore } from '@/utils/localUser.js'
import router from '@/router/index.js'
import { MENUS, TOKEN, USERINFO } from '@/utils/const.js'
import registerRouter from '@/utils/addRoute.js'
import responseMessage from '@/utils/response.js'
import {
  addUserInfo,
  editUser,
  editUserInfo,
  editUserPassword,
  getLoginCheckCode,
  getUserInfo,
  getUserListInfo,
  login,
  loginOut,
  removeBatchUserByUserIds,
  removeUserByUserId,
  resetPassword
} from '@/service/index.js'
import useDeptStore from '@/store/dept/index.js'
import useMenuStore from '@/store/menu/index.js'
import { watch } from 'vue'
import { changeTree } from '@/utils/treeUtils.js'

const useLoginStore = defineStore('login', {
  state: () => ({
    codeImage: '',
    userInfo: getLocalStore(USERINFO) ?? '',
    token: getLocalStore(TOKEN) ?? '',
    menus: getLocalStore(MENUS) ?? '',
    personInfo: '',
    userList: [],
    totalCount: ''
  }),
  actions: {
    async getLoginCodeImageAction() {
      const res = await getLoginCheckCode()
      this.codeImage = res.data
    },
    async loginAction(user) {
      const res = await login(user)
      if (res.code !== 1) {
        ElMessage.error(res.msg)
        return
      }
      this.userInfo = res.data
      this.token = res.data.token
      this.menus = res.data.menus

      //加载tree
      this.loginLoadTree()
      //存储用户信息
      setLocalStore(TOKEN, res.data.token)
      setLocalStore(MENUS, this.userInfo.menus)
      setLocalStore(USERINFO, this.userInfo)
      ElMessage.success('登录成功')

      //获取用户需要注册的路由
      const registerRoute = registerRouter(this.userInfo.menus)
      console.log('注册的路由信息：', registerRoute)
      registerRoute.forEach((item) => router.addRoute('main', item))
      //跳转页面
      await router.push('/main')
    },

    //刷新页面加载路由信息
    loadRouterData() {
      const token = getLocalStore(TOKEN)
      const userMenus = getLocalStore(MENUS)
      const userInfo = getLocalStore(USERINFO)
      if (token && userInfo && userMenus) {
        this.token = token
        this.menus = userMenus
        this.userInfo = userInfo

        //加载菜单和部门数据
        this.loginLoadTree()
        //注册路由
        const routes = registerRouter(userMenus)
        routes.forEach((item) => router.addRoute('main', item))
      }
    },

    //加载菜单和部门数据
    loginLoadTree() {
      //获取菜单信息和部门信息,数据量大提前加载
      const deptStore = useDeptStore()
      const menuStore = useMenuStore()
      deptStore.getDeptTreeAction()
      menuStore.getMenuTreeAction()
      const { menuTree } = storeToRefs(menuStore)
      const { deptTree } = storeToRefs(deptStore)
      // 转化tree
      watch(menuTree, () => {
        changeTree(menuTree.value, 'menuName', 'label', 'menuId', 'value')
      })
      //转化tree
      watch(deptTree, () => {
        changeTree(deptTree.value, 'deptName', 'label', 'deptId', 'value')
      })
    },

    //基本信息修改
    async editUserInfoAction(baseInfo) {
      const res = await editUserInfo(baseInfo)
      responseMessage(res, '修改成功')
    },
    //修改用户密码
    async editUserPasswordAction(oldPassword, newPassword) {
      const res = await editUserPassword(oldPassword, newPassword)
      responseMessage(res, '修改成功')
    },
    //退出登录
    async loginOutAction() {
      const res = await loginOut()
      responseMessage(res, '退出成功')
    },

    //获取个人中心信息
    async getUserInfoAction() {
      const res = await getUserInfo()
      this.personInfo = res.data
    },
    //分页获取用户数据
    async getUserListInfoAction(page, size, searchParams) {
      const res = await getUserListInfo(page, size, searchParams)
      this.userList = res.data.records
      this.totalCount = res.data.total
    },
    //删除用户信息
    async removeUserByUserIdAction(userId) {
      const res = await removeUserByUserId(userId)
      responseMessage(res, '删除成功')
    },
    //批量删除用户信息
    async removeBatchUserByUserIdsAction(userIds) {
      const res = await removeBatchUserByUserIds(userIds)
      responseMessage(res)
    },
    //用户列表重置密码
    async resetPasswordAction(userId) {
      const res = await resetPassword(userId)
      responseMessage(res)
    },
    //新增用户信息
    async addUserInfoAction(userInfo) {
      const res = await addUserInfo(userInfo)
      responseMessage(res)
      return res
    },
    //编辑用户信息
    async editUserAction(userInfo) {
      const res = await editUser(userInfo)
      responseMessage(res)
      return res
    }
  }
})
export default useLoginStore
